package com.example.word.ui.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.dict.R;
import com.example.word.bean.Collect;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.User;
import com.example.word.bean.Word;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学习计划
 */
public class StudyPlanActivity extends AppCompatActivity {
    private Activity mActivity;
    private ActionBar mTitleBar;//标题栏
    private TextView tvAccount, tvDayTask;
    private Button btnSave;//保存
    private Spinner dictSelect;
    private String account;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study_plan);
        mActivity = this;
        tvAccount = findViewById(R.id.tv_account);
        tvDayTask = findViewById(R.id.dayTask);
        btnSave = findViewById(R.id.btn_save);
        dictSelect = findViewById(R.id.dictSelect);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(mActivity, "学习计划", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
        initView();
    }

    private void initView() {
        account = (String) SPUtils.get(mActivity, "account", "");
        // 获取当前用户信息
        HttpUtils.sendGetRequest("/getUserByAccount", new HashMap<>(), mActivity, User.class, (HttpUtils.ApiCallback<User>) response -> {
            // 处理请求成功的情况
            User user = response.getData();
            tvAccount.setText(user.getAccount() + " (" + user.getNickName() + ")");
        });


        HttpUtils.sendGetRequest("/getDictList", new HashMap<>(), mActivity, Dict.class, response -> {
            List<Dict> dictList = response.getDataList();
            List<String> itemsArray = new ArrayList<>();
            for (Dict dict : dictList) {
                itemsArray.add(dict.getDict());
            }
            // 创建 ArrayAdapter 并设置下拉选项的样式
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, itemsArray);
            // 设置下拉列表的样式
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // 将适配器设置到 Spinner
            dictSelect.setAdapter(adapter);

            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/getUserStudyPlan", new HashMap<>(), mActivity, StudyPlan.class, studyPlanResponse -> {
                // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
                StudyPlan studyPlan = studyPlanResponse.getData();
                tvDayTask.setText(String.valueOf(studyPlan.getDayTask()));
                dictSelect.setSelection(itemsArray.indexOf(studyPlan.getDict()));
            });
        });

        //保存
        btnSave.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                int dayTask = 0;
                String dict = null;
                try {
                    dayTask = Integer.parseInt(tvDayTask.getText().toString());
                    dict = dictSelect.getSelectedItem().toString();
                } catch (Exception e) {
                    MessageUtils.show("请填写完整信息", mActivity);
                    return;
                }

                if ("".equals(dict)) {
                    MessageUtils.show("词汇不能为空", mActivity);
                    return;
                }
                if (dayTask <= 0) {
                    MessageUtils.show("任务数必须大于0", mActivity);
                    return;
                }

                Map<String, String> requestParam = new HashMap<>();
                requestParam.put("dict", dict);
                requestParam.put("dayTask", String.valueOf(dayTask));
                HttpUtils.sendGetRequest("/saveStudyPlan", requestParam, mActivity, StudyPlan.class, collectResponse -> {
                    StudyPlan responseData = collectResponse.getData();
                    MessageUtils.show("保存成功！", mActivity);

                    String message = String.format("您正在学习【%s】每天目标为%s个单词！", responseData.getDict(), responseData.getDayTask());

                    sendNotify(message, mActivity);

                    finish();//关闭页面
                });

            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void sendNotify(String message, Context context) {
        StudyPlan studyPlan;// 创建通知渠道（仅适用于 Android 8.0 及以上）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel Description");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        // 创建通知
        Notification.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            builder = new Notification.Builder(context, "channel_id")
                    .setSmallIcon(R.drawable.a1)
                    .setContentTitle("学习计划制定成功")
                    .setContentText(message)
                    .setPriority(Notification.PRIORITY_DEFAULT);
        }

        // 使用通知管理器显示通知
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.notify((int) Math.floor(Math.random() * 10), builder.build());
    }
}
